package com.jnshu.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jnshu.constant.Constant;
import com.jnshu.dao.*;
import com.jnshu.dto.course.ContentVo;
import com.jnshu.dto.course.CourseDto;
import com.jnshu.dto.course.CourseVo;
import com.jnshu.dto.course.VideoVo;
import com.jnshu.pojo.*;
import com.jnshu.service.FrontCourseService;
import com.jnshu.tools.HeadUtil;
import com.jnshu.tools.binding.RedisUtil;
import com.jnshu.tools.resultUtils.RUtil;
import com.jnshu.tools.resultUtils.ResultBean;
import com.jnshu.tools.resultUtils.ResultEnum;
import lombok.extern.java.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

/**
 * @ClassName FrontCourseServiceImpl
 * @Descrintion
 * @Author bd
 * @Date 2019/8/7 15:08
 * @Version 1.0
 **/
@Service
@Log
public class FrontCourseServiceImpl implements FrontCourseService {
    @Autowired(required = false)
    CourseMapper courseMapper;
    @Autowired(required = false)
    HeadUtil headUtil;
    @Autowired(required = false)
    HistoryMapper historyMapper;
    @Autowired(required = false)
    ViewMapper viewMapper;
    @Autowired(required = false)
    CollectMapper collectMapper;
    @Autowired(required = false)
    TaskMapper taskMapper;
    @Autowired(required = false)
    UserMapper userMapper;
    @Autowired(required = false)
    UserTaskRelationMapper userTaskRelationMapper;

    //文章、视频列表
    @Override

    public ResultBean uSelectList(CourseDto course, int pageSize, int pageNum, Long userId) {
        log.info("service层传入的前台查询参数为course" + course + ",页面数量为" + pageSize + ",页码" + pageNum);
        Page page = PageHelper.startPage(pageNum, pageSize);
        List<CourseVo> courseVos = courseMapper.uSelectList(course);
        log.info("数据库中查询的数据为" + courseVos);
        PageInfo<CourseVo> info = new PageInfo<>(courseVos);
        log.info("分页后的数据为" + info);

        if (course.getTitle() != null) {

            if (course.getClassify() == 0) {
                String ids = userId + "0";
                long res = RedisUtil.lpush(ids, course.getTitle());
                log.info("redis缓存记录返回list的value个数" + res);
            }
            if (course.getClassify() == 1) {
                String ids = userId + "1";
                long res = RedisUtil.lpush(ids, course.getTitle());
                log.info("redis缓存记录返回list的value个数" + res);
            }
        }

        if (info == null) {
            return RUtil.error(ResultEnum.NOTHINGNESS);
        } else {
            return RUtil.ok(info);
        }

    }

    //文章详情

    @Override
    public ResultBean selectByPrimaryKey(long id, Long userId) {
        log.info("service层传入的前台查询详情参数为id" + id);
        try {
            Course course = courseMapper.selectByPrimaryKey(id);
            ContentVo contentVo = new ContentVo();
            BeanUtils.copyProperties(course, contentVo);

            if (contentVo == null) {
                return RUtil.error(ResultEnum.NOTHINGNESS);
            } else {
                //插入历史记录
                History historys = historyMapper.selectRecord(userId, id);
                History history = new History();
                if (historys == null) {

                    //插入历史记录
                    ;
                    history.setCourseId(id);
                    history.setUserId(userId);
                    history.setType(0);
                    history.setCreateAt(System.currentTimeMillis());
                    history.setUpdateAt(System.currentTimeMillis());
                    history.setCreateBy(userId);
                    history.setUpdateBy(userId);
                    int a = historyMapper.insert(history);
                    log.info("插入历史表记录为" + a);
                } else {
                    history.setUpdateAt(System.currentTimeMillis());
                    history.setUpdateBy(userId);
                    historyMapper.updateByPrimaryKeySelective(history);
                }

                //插入浏览记录表

                View views = viewMapper.selectRecord(userId, id);

                if (views == null) {

                    View view = new View();
                    view.setCourseId(id);
                    view.setUserId(userId);
                    view.setCreateAt(System.currentTimeMillis());
                    view.setUpdateAt(System.currentTimeMillis());
                    view.setCreateBy(userId);
                    view.setUpdateBy(userId);
                    int b = viewMapper.insert(view);
                    log.info("插入浏览记录表表记录为" + b);

                    //查询阅读量，也可以直接自增，不用查询
                    int viewAmount = (int) viewMapper.selectCount(id);
                    //  插入阅读量
                    courseMapper.updateView(id, viewAmount);
                }

                //查找任务
                Task task = taskMapper.selectById("浏览1篇教辅资料");
                if (task != null) {
                    Integer integral = userMapper.selectIntegral(userId);
                    UserTaskRelation relation = userTaskRelationMapper.selectByUserId(userId, task.getId());

                    if (relation != null) {
                        long time = relation.getUpdateAt();
                        long current = System.currentTimeMillis();//当前时间毫秒数
                        long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
                        long twelve = zero + 24 * 60 * 60 * 1000 - 1;//今天23点59分59秒的毫秒数
                        if (zero < time && time < twelve) {
                            log.info("已做过此任务");
                        } else {
                            //更新积分状态，添加数据到关系表
                            integral = integral + task.getPointReward();
                            boolean rs = userMapper.updateIntegral(userId, integral);
                            log.info("积分更新状态" + rs);
                            UserTaskRelation userTaskRelation = new UserTaskRelation();
                            userTaskRelation.setUpdateAt(System.currentTimeMillis());
                            userTaskRelation.setStatus(1);
                            userTaskRelation.setTaskId(7L);
                            userTaskRelation.setUserId(userId);
                            userTaskRelationMapper.updateByPrimaryKeySelective(userTaskRelation);

                        }

                    } else {
                        //更新积分状态，添加数据到关系表
                        integral = integral + task.getPointReward();
                        boolean rs = userMapper.updateIntegral(userId, integral);
                        log.info("积分更新状态" + rs);
                        UserTaskRelation userTaskRelation = new UserTaskRelation();
                        userTaskRelation.setUserId(userId);
                        userTaskRelation.setTaskId(task.getId());
                        userTaskRelation.setStatus(1);
                        userTaskRelation.setCreateAt(System.currentTimeMillis());
                        userTaskRelation.setUpdateAt(System.currentTimeMillis());
                        userTaskRelationMapper.insertSelective(userTaskRelation);
                    }
                }
                return RUtil.ok(contentVo);
            }

        } catch (Exception e) {
            log.info("执行查找过程中是失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RUtil.error(ResultEnum.FAILURE);

        }


    }


    //视频详情
    @Override
    public ResultBean selectByPrimaryKeyVideo(long id, Long userId) {
        log.info("service层传入的前台查询详情参数为id" + id);
        try {
            Course course = courseMapper.selectByPrimaryKey(id);

            log.info(" course " + course);
            VideoVo videoVo = new VideoVo();
            BeanUtils.copyProperties(course, videoVo);
            log.info("videoVo" + videoVo);

            if (videoVo == null) {
                return RUtil.error(ResultEnum.Message_Status_Fail);
            } else {
                //插入历史记录
                History historys = historyMapper.selectRecord(userId, id);
                log.info("historys" + historys);
                History history = new History();
                if (historys == null) {

                    //插入历史记录

                    history.setCourseId(id);
                    history.setUserId(userId);
                    history.setType(1);
                    history.setCreateAt(System.currentTimeMillis());
                    history.setUpdateAt(System.currentTimeMillis());
                    history.setCreateBy(userId);
                    history.setUpdateBy(userId);
                    int a = historyMapper.insert(history);
                    log.info("插入历史表记录为" + history);
                } else {
                    history.setUpdateAt(System.currentTimeMillis());
                    history.setUpdateBy(userId);
                    historyMapper.updateByPrimaryKeySelective(history);

                }

                //插入浏览记录表
                View views = viewMapper.selectRecord(userId, id);
                log.info("views" + views);
                if (views == null) {

                    View view = new View();
                    view.setCourseId(id);
                    view.setUserId(userId);
                    view.setCreateAt(System.currentTimeMillis());
                    view.setUpdateAt(System.currentTimeMillis());
                    view.setCreateBy(userId);
                    view.setUpdateBy(userId);
                    int b = viewMapper.insert(view);
                    log.info("插入浏览记录表表记录为" + b);

                    //查询阅读量，也可以直接自增，不用查询
                    int viewAmount = (int) viewMapper.selectCount(id);
                    //  插入阅读量
                    courseMapper.updateView(id, viewAmount);
                }

                //查找任务
                Task task = taskMapper.selectById("浏览1篇趣味视频");
                if (task != null) {

                    Integer integral = userMapper.selectIntegral(userId);
                    UserTaskRelation relation = userTaskRelationMapper.selectByUserId(userId, task.getId());

                    if (relation != null) {
                        long time = relation.getUpdateAt();
                        long current = System.currentTimeMillis();//当前时间毫秒数
                        long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
                        long twelve = zero + 24 * 60 * 60 * 1000 - 1;//今天23点59分59秒的毫秒数
                        if (zero < time && time < twelve) {
                            log.info("已做过此任务");
                        } else {
                            //更新积分状态，添加数据到关系表
                            integral = integral + task.getPointReward();
                            boolean rs = userMapper.updateIntegral(userId, integral);
                            log.info("积分更新状态" + rs);
                            UserTaskRelation userTaskRelation = new UserTaskRelation();

                            userTaskRelation.setUpdateAt(System.currentTimeMillis());
                            userTaskRelation.setStatus(1);
                            userTaskRelation.setTaskId(8L);
                            userTaskRelation.setUserId(userId);
                            userTaskRelationMapper.updateByPrimaryKeySelective(userTaskRelation);

                        }

                    } else {
                        //更新积分状态，添加数据到关系表
                        integral = integral + task.getPointReward();
                        boolean rs = userMapper.updateIntegral(userId, integral);
                        log.info("积分更新状态" + rs);
                        UserTaskRelation userTaskRelation = new UserTaskRelation();
                        userTaskRelation.setUserId(userId);
                        userTaskRelation.setTaskId(task.getId());
                        userTaskRelation.setStatus(1);
                        userTaskRelation.setCreateAt(System.currentTimeMillis());
                        userTaskRelation.setUpdateAt(System.currentTimeMillis());
                        userTaskRelationMapper.insertSelective(userTaskRelation);
                    }
                }

                return RUtil.ok(videoVo);
            }
        } catch (
                Exception e) {
            log.info("执行查找过程中是失败" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RUtil.error(ResultEnum.FAILURE);

        }
    }

    //收藏
    @Override
    public ResultBean insert(Integer classify, Long courseId, Long userId) {

        Collect collect = new Collect();


        collect.setClassify(classify);
        collect.setCourseId(courseId);
        collect.setUserId(userId);
        collect.setCreateAt(System.currentTimeMillis());
        collect.setUpdateAt(System.currentTimeMillis());
        collect.setUpdateBy(userId);
        collect.setCreateBy(userId);
        log.info("service层insert方法传入的参数为" + collect);

        int collects = collectMapper.insert(collect);

        //查找任务
        Task task = taskMapper.selectById("收藏一篇文章或一个视频");
        if (task != null) {
            Integer integral = userMapper.selectIntegral(userId);
            UserTaskRelation relation = userTaskRelationMapper.selectByUserId(userId, task.getId());

            if (relation != null) {
//                long time = relation.getUpdateAt();
//                long current = System.currentTimeMillis();//当前时间毫秒数
//                long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
//                long twelve = zero + 24 * 60 * 60 * 1000 - 1;//今天23点59分59秒的毫秒数
                Integer statu = relation.getStatus();

                if (statu==1) {
                    log.info("已做过此任务");
                } else {
                    //更新积分状态，添加数据到关系表
                    integral = integral + task.getPointReward();
                    boolean rs = userMapper.updateIntegral(userId, integral);
                    log.info("积分更新状态" + rs);
                    UserTaskRelation userTaskRelation = new UserTaskRelation();
                    userTaskRelation.setUpdateAt(System.currentTimeMillis());
                    userTaskRelation.setStatus(1);
                    userTaskRelation.setTaskId(9L);
                    userTaskRelation.setUserId(userId);
                    userTaskRelationMapper.updateByPrimaryKeySelective(userTaskRelation);

                }

            } else {
                //更新积分状态，添加数据到关系表
                integral = integral + task.getPointReward();
                boolean rs = userMapper.updateIntegral(userId, integral);
                log.info("积分更新状态" + rs);
                UserTaskRelation userTaskRelation = new UserTaskRelation();
                userTaskRelation.setUserId(userId);
                userTaskRelation.setTaskId(task.getId());
                userTaskRelation.setStatus(1);
                userTaskRelation.setCreateAt(System.currentTimeMillis());
                userTaskRelation.setUpdateAt(System.currentTimeMillis());
                userTaskRelationMapper.insertSelective(userTaskRelation);
            }

        }


        if (collects == 0) {
            return RUtil.error(ResultEnum.FAILURE);
        } else {
            return RUtil.ok();
        }
    }

    //收藏状态
    @Override
    public ResultBean selectStatus(Long courseId, Long userId) {
        log.info("service层selectStatus方法传入的参数courseId为" + courseId + "参数userId为" + userId);

        Collect collect = collectMapper.selectStatus(userId, courseId);
        log.info("数据库中的数据为" + collect);
        if (collect == null) {
            int i = 0;
            return RUtil.ok(i);
        } else {
            int i = 1;
            return RUtil.ok(i);

        }
    }

    //取消收藏状态
    @Override
    public ResultBean deleteStatus(Long courseId, Long userId) {
        log.info("service层deleteStatus方法传入的参数courseId为" + courseId);

        Collect collect = collectMapper.selectStatus(userId, courseId);
        if (collect == null) {
            return RUtil.error(600, "用户未未收藏");
        } else {
            boolean a = collectMapper.deleteStatus(userId, courseId);
            //查找任务
            Task task = taskMapper.selectById("收藏");
            if (task != null) {
                Integer integral = userMapper.selectIntegral(userId);
                UserTaskRelation relation = userTaskRelationMapper.selectByUserId(userId, task.getId());

                if (relation != null) {
                    long time = relation.getUpdateAt();
                    long current = System.currentTimeMillis();//当前时间毫秒数
                    long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
                    long twelve = zero + 24 * 60 * 60 * 1000 - 1;//今天23点59分59秒的毫秒数
                    if (zero < time && time < twelve) {
                        log.info("取消任务扣除分数");
                        integral = integral - task.getPointReward();
                        boolean rs = userMapper.updateIntegral(userId, integral);
                        log.info("积分更新状态" + rs);
                    }

                } else {
                    log.info("没有收藏任务");

                }

            }

            if (a == true) {
                return RUtil.ok();
            } else {
                return RUtil.error();
            }
        }
    }

    @Override
    //历史记录
    public ResultBean getHistory(Integer classify, String userId) {

        String ids = userId + String.valueOf(classify);

        List<String> list = RedisUtil.lrange(ids, 0, -1);
        if (list == null || list.size() == 0) {
            list = new ArrayList<String>();
        }
        return RUtil.ok(list);
    }

    //删除历史记录
    @Override
    public ResultBean deleteHistory(Integer classify, String userId) {

        String ids = userId + String.valueOf(classify);
        try {
            Long res = RedisUtil.del(ids);
            return RUtil.ok();
        } catch (Exception e) {
            return RUtil.error(ResultEnum.FAILURE);
        }

    }
}
